package com.efast.dmom.mgmt.controller.excel;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.efast.cafe.framework.bean.FileChunkInfo;
import com.efast.cafe.framework.bean.ResultBean;
import com.efast.dmom.mgmt.bean.excel.ExcelRuleDataBean;
import com.efast.dmom.mgmt.service.excel.AssociatedTableExcelFileImportService;
import com.efast.dmom.mgmt.service.excel.ExcelTemplateExportCommonService;
import com.efast.dmom.mgmt.service.excel.UploadExcelFileService;

/**
 * 
 * @author wj
 * 2019/10/16
 *
 */
@Controller
@RequestMapping(value = "/uploadExcelFileCommen")
public class UploadExcelFileCommenController {
	
	@Autowired
	private UploadExcelFileService uploadExcelFileService;
	
	@Autowired
	private ExcelTemplateExportCommonService excelTemplateExportCommonService;
	
	@Autowired
	private AssociatedTableExcelFileImportService associatedTableExcelFileImportService;
	
	//按字段名称上传文件
	@RequestMapping(value = "/uploadByQueryField", method = RequestMethod.POST)
	public @ResponseBody ResultBean uploadByQueryField(@RequestParam("files") MultipartFile mulFile, String ruleData
			,String tableName,Integer rowNumber,HttpServletResponse response,
		       HttpServletRequest request, FileChunkInfo chunkInfo) throws IOException{
		 ResultBean resultBean = new ResultBean(true,"'");
		 List<ExcelRuleDataBean> data= JSON.parseObject(ruleData,new TypeReference<List<ExcelRuleDataBean>>(){});
		 int id = 0;
		 for(ExcelRuleDataBean bean:data) {
			 if(bean.getRepeatField() != null) {
				 id = id+1;
			 }
		 }
		 if(id>1) {
			 resultBean.setSuccess(false);
			 resultBean.setMessage("查重字段不唯一！"); 
			 return resultBean;
		 }
		 if(mulFile==null||mulFile.isEmpty()) {
			 resultBean.setSuccess(false);
			 resultBean.setMessage("上传失败，请重新上传！");
			 return resultBean;
		 }else if(mulFile.getSize()>10000000) {
			 resultBean.setSuccess(false);
			 resultBean.setMessage("上传失败，文件大小不能超过10M!！");
			 return resultBean;
		 }else {
			 String rootPath = request.getServletContext().getRealPath("/") + "uploadExcel";
//		     File tempFile = FileUploadUtil.getReadySpace(chunkInfo, rootPath);
		     //文件所在的临时文件夹
		     String fileName = chunkInfo.getFileName();
//		     String flodName = fileName.substring(0, fileName.lastIndexOf(".")) + chunkInfo.getUuid();
//		     String flodName=fileName.substring(0, fileName.lastIndexOf("."));
		     File dir = new File(rootPath);
		     if(!dir.exists()){
					dir.mkdir();
			 	}
//				String chunkName = +fileName.substring(fileName.lastIndexOf('.'));
				File chunkFile = new File(dir, fileName);
					try {
						chunkFile.createNewFile();
					} catch (IOException e) {
						e.printStackTrace();
					}
		     mulFile.transferTo(chunkFile);
		     uploadExcelFileService.uploadByQueryField(chunkFile,tableName,data,rowNumber);
		     chunkFile.delete();
	         resultBean.setSuccess(true);
			 resultBean.setMessage("文件上传成功");
		 }
		 return resultBean;
//		
		} 

	
	
	//规则查询方式上传文件
		@RequestMapping(value = "/uploadByQueryRule", method = RequestMethod.POST)
		public @ResponseBody ResultBean uploadByQueryRule(@RequestParam("files") MultipartFile mulFile, Integer rowNumber,String tableName,HttpServletResponse response,
			       HttpServletRequest request, FileChunkInfo chunkInfo) throws IOException{
			 ResultBean resultBean = new ResultBean(true,"'");
			 if(mulFile==null||mulFile.isEmpty()) {
				 resultBean.setSuccess(false);
				 resultBean.setMessage("上传失败，请重新上传！");
			 }else if(mulFile.getSize()>10000000) {
				 resultBean.setSuccess(false);
				 resultBean.setMessage("上传失败，文件大小不能超过10M!！");
			 }else {
				 String rootPath = request.getServletContext().getRealPath("/") + "uploadExcel";
//			     File tempFile = FileUploadUtil.getReadySpace(chunkInfo, rootPath);
			     //文件所在的临时文件夹
			     String fileName = chunkInfo.getFileName();
//			     String flodName = fileName.substring(0, fileName.lastIndexOf(".")) + chunkInfo.getUuid();
//			     String flodName=fileName.substring(0, fileName.lastIndexOf("."));
			     File dir = new File(rootPath);
			     if(!dir.exists()){
						dir.mkdir();
				 	}
//					String chunkName = +fileName.substring(fileName.lastIndexOf('.'));
					File chunkFile = new File(dir, fileName);
						try {
							chunkFile.createNewFile();
						} catch (IOException e) {
							e.printStackTrace();
						}
			     mulFile.transferTo(chunkFile);
			     uploadExcelFileService.uploadByQueryRule(chunkFile,tableName,rowNumber);
			     chunkFile.delete();
		         resultBean.setSuccess(true);
				 resultBean.setMessage("文件上传成功");
			 }
			 return resultBean;
			} 
		
		
		//excel模板数据上传
	     @RequestMapping(value = "/excelTemplateDataUpload", method = RequestMethod.POST)
		 public @ResponseBody ResultBean uploadExcelFile(@RequestParam("files") MultipartFile mulFile,String entityName,HttpServletResponse response,
	     HttpServletRequest request, FileChunkInfo chunkInfo) throws IOException{
	    	 ResultBean resultBean = new ResultBean(true,"'");
	    	 String tableName=excelTemplateExportCommonService.selectTableNameByentityName(entityName);
			 if(mulFile==null||mulFile.isEmpty()) {
				 resultBean.setSuccess(false);
				 resultBean.setMessage("上传失败，请重新上传！");
			 }else if(mulFile.getSize()>10000000) {
				 resultBean.setSuccess(false);
				 resultBean.setMessage("上传失败，文件大小不能超过10M!！");
			 }else {
				 String rootPath = request.getServletContext().getRealPath("/") + "uploadExcel";
//			     File tempFile = FileUploadUtil.getReadySpace(chunkInfo, rootPath);
			     //文件所在的临时文件夹
			     String fileName = chunkInfo.getFileName();
//			     String flodName = fileName.substring(0, fileName.lastIndexOf(".")) + chunkInfo.getUuid();
//			     String flodName=fileName.substring(0, fileName.lastIndexOf("."));
			     File dir = new File(rootPath);
			     if(!dir.exists()){
						dir.mkdir();
				 	}
//					String chunkName = +fileName.substring(fileName.lastIndexOf('.'));
					File chunkFile = new File(dir, fileName);
						try {
							chunkFile.createNewFile();
						} catch (IOException e) {
							e.printStackTrace();
						}
			     mulFile.transferTo(chunkFile);
			     ResultBean uploadExcelFile = uploadExcelFileService.uploadExcelFile(chunkFile,tableName);
			     if (!uploadExcelFile.success) {
			    	 uploadExcelFile.setSuccess(true);
			    	 chunkFile.delete();
			    	 return uploadExcelFile;
			     }
			     chunkFile.delete();
		         resultBean.setSuccess(true);
				 resultBean.setMessage("文件上传成功");
			 }
			 return resultBean;
	     }

	   //物料基础数据excel模板数据上传
	     @RequestMapping(value = "/bomItemExcelTemplateDataUpload", method = RequestMethod.POST)
		 public @ResponseBody ResultBean bomItemExcelTemplateDataUpload(@RequestParam("files") MultipartFile mulFile,String entityName,HttpServletResponse response,
	     HttpServletRequest request, FileChunkInfo chunkInfo) throws IOException{
	    	 ResultBean resultBean = new ResultBean(true,"'");
	    	 String tableName=excelTemplateExportCommonService.selectTableNameByentityName(entityName);
			 if(mulFile==null||mulFile.isEmpty()) {
				 resultBean.setSuccess(false);
				 resultBean.setMessage("上传失败，请重新上传！");
			 }else if(mulFile.getSize()>10000000) {
				 resultBean.setSuccess(false);
				 resultBean.setMessage("上传失败，文件大小不能超过10M!！");
			 }else {
				 String rootPath = request.getServletContext().getRealPath("/") + "uploadExcel";
//			     File tempFile = FileUploadUtil.getReadySpace(chunkInfo, rootPath);
			     //文件所在的临时文件夹
			     String fileName = chunkInfo.getFileName();
//			     String flodName = fileName.substring(0, fileName.lastIndexOf(".")) + chunkInfo.getUuid();
//			     String flodName=fileName.substring(0, fileName.lastIndexOf("."));
			     File dir = new File(rootPath);
			     if(!dir.exists()){
						dir.mkdir();
				 	}
//					String chunkName = +fileName.substring(fileName.lastIndexOf('.'));
					File chunkFile = new File(dir, fileName);
						try {
							chunkFile.createNewFile();
						} catch (IOException e) {
							e.printStackTrace();
						}
			     mulFile.transferTo(chunkFile);
			     uploadExcelFileService.bomItemUploadExcelFile(chunkFile,tableName);
			     chunkFile.delete();
		         resultBean.setSuccess(true);
				 resultBean.setMessage("文件上传成功");
			 }
			 return resultBean;
	     }
	   //物料基础数据excel模板数据上传
	     @RequestMapping(value = "/partExcelTemplateDataUpload", method = RequestMethod.POST)
		 public @ResponseBody ResultBean partUploadExcelFile(@RequestParam("files") MultipartFile mulFile,String entityName,HttpServletResponse response,
	     HttpServletRequest request, FileChunkInfo chunkInfo) throws IOException{
	    	 ResultBean resultBean = new ResultBean(true,"'");
	    	 String tableName=excelTemplateExportCommonService.selectTableNameByentityName(entityName);
			 if(mulFile==null||mulFile.isEmpty()) {
				 resultBean.setSuccess(false);
				 resultBean.setMessage("上传失败，请重新上传！");
			 }else if(mulFile.getSize()>10000000) {
				 resultBean.setSuccess(false);
				 resultBean.setMessage("上传失败，文件大小不能超过10M!！");
			 }else {
				 String rootPath = request.getServletContext().getRealPath("/") + "uploadExcel";
//			     File tempFile = FileUploadUtil.getReadySpace(chunkInfo, rootPath);
			     //文件所在的临时文件夹
			     String fileName = chunkInfo.getFileName();
//			     String flodName = fileName.substring(0, fileName.lastIndexOf(".")) + chunkInfo.getUuid();
//			     String flodName=fileName.substring(0, fileName.lastIndexOf("."));
			     File dir = new File(rootPath);
			     if(!dir.exists()){
						dir.mkdir();
				 	}
//					String chunkName = +fileName.substring(fileName.lastIndexOf('.'));
					File chunkFile = new File(dir, fileName);
						try {
							chunkFile.createNewFile();
						} catch (IOException e) {
							e.printStackTrace();
						}
			     mulFile.transferTo(chunkFile);
			     uploadExcelFileService.partUploadExcelFile(chunkFile,tableName);
			     chunkFile.delete();
		         resultBean.setSuccess(true);
				 resultBean.setMessage("文件上传成功");
			 }
			 return resultBean;
	     }


	  // 源码规则Excel文件关联导入
	 	@RequestMapping(value = "/barcodeRuleExcelUpload", method = RequestMethod.POST)
	 	public @ResponseBody ResultBean barcodeRuleExcelUpload(@RequestParam("files") MultipartFile mulFile,String entityName,
	 			HttpServletResponse response, HttpServletRequest request, FileChunkInfo chunkInfo) throws IOException {
	 		ResultBean resultBean = new ResultBean(true, "'");
	 		if (mulFile == null || mulFile.isEmpty()) {
	 			resultBean.setSuccess(false);
	 			resultBean.setMessage("上传失败，请重新上传！");
	 		} else if (mulFile.getSize() > 10000000) {
	 			resultBean.setSuccess(false);
	 			resultBean.setMessage("上传失败，文件大小不能超过10M!！");
	 		} else {
	 			String rootPath = request.getServletContext().getRealPath("/") + "uploadExcel";
	 			// 文件所在的临时文件夹
	 			String fileName = chunkInfo.getFileName();
	 			File dir = new File(rootPath);
	 			if (!dir.exists()) {
	 				dir.mkdir();
	 			}
	 			File chunkFile = new File(dir, fileName);
	 			try {
	 				chunkFile.createNewFile();
	 			} catch (IOException e) {
	 				e.printStackTrace();
	 			}
	 			mulFile.transferTo(chunkFile);
	 			associatedTableExcelFileImportService.uploadExcelFile(chunkFile);
	 			chunkFile.delete();
	 			resultBean.setSuccess(true);
	 			resultBean.setMessage("文件上传成功");
	 		}
	 		return resultBean;
	 	}
	 	
	 	// 上传图片到指定loginLogo
	 	@RequestMapping(value = "/loginLogo", method = RequestMethod.POST)
	 	public @ResponseBody ResultBean loginLogo(@RequestParam("files") MultipartFile mulFile, String id,
	 			HttpServletResponse response, HttpServletRequest request, FileChunkInfo chunkInfo) throws IOException {
	 		ResultBean resultBean = new ResultBean(true);
	 		byte[] bs = mulFile.getBytes();
	 		 if (bs.length > 0) {
	 			try {
//	 				 String filePath = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
//	 				filePath = java.net.URLDecoder.decode(filePath, "utf-8");
	 				String filePath = "D:\\image";
	 				File validateCodeFolder = new File(filePath);
	 				if (!validateCodeFolder.exists()) {
	 				     validateCodeFolder.mkdirs();
	 				    }
	 			// 将字符串转换成二进制，用于显示图片
	 			// 将上面生成的图片格式字符串 imgStr，还原成图片显示
	 			    String uuid = "";
	 				if (id.equals("1")) {
	 					uuid = "loginLogo";
	 				} else if (id.equals("2")) {
	 					uuid = "bg";
	 				} else if (id.equals("3")) {
	 					uuid = "MainLogo";
	 				} else {
	 					resultBean.setErrorCode("传入数据无法识别替换哪个背景");
	 					return resultBean;
	 				}
	 			   int lastIndexOf = chunkInfo.getFileName().lastIndexOf(".");
	 			  String Imgtype = chunkInfo.getFileName().substring(lastIndexOf);
	 			  String type = Imgtype;
	 			   String filename = uuid + type;
	 			    InputStream in = new ByteArrayInputStream(bs);
	 			   File file = new File(filePath, filename);// 可以是任何图片格式.jpg,.png等
	 			  FileOutputStream fos = new FileOutputStream(file);
	 			 byte[] b = new byte[1024];
	 			int nRead = 0;
	 		    while ((nRead = in.read(b)) != -1) {
	 		     fos.write(b, 0, nRead);
	 		    }
	 		   fos.flush();
	 		    fos.close();
	 		    in.close();
//	 		   json.addProperty("code", 200);
//	 		  json.addProperty("msg", filePath + chunkInfo.getFileName());
//	 		  String str = json.toString();
//	 		  response.setCharacterEncoding("utf-8");
//	 		  response.setHeader("content-type", "text/html;charset=UTF-8");
//	 		  response.getWriter().write(str);
//	 		  response.getWriter().flush();
//	 		  response.getWriter().close();
	 		    InetAddress localHost = InetAddress.getLocalHost();
	 		   String hostAddress = localHost.getHostAddress();
	 		   resultBean.setObject(hostAddress+filePath+"/"+filename);
				} catch (Exception e) {
				    e.printStackTrace();
				}
	 		 } else {
	 			resultBean.setErrorCode("上传失败");
	 		 }
					return resultBean;
	 	}
	 	
}
